﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Croxweb.Leuphana.Models;
using Croxweb.Leuphana.ViewModels;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace Croxweb.Leuphana.Pages
{
    public partial class LecturePage : PhoneApplicationPage
    {
        private LectureViewModel viewModel;

        public LecturePage()
        {
            InitializeComponent();

            // Datacontext to view model.
            viewModel = new LectureViewModel();
            DataContext = viewModel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            String id;
            NavigationContext.QueryString.TryGetValue("id", out id);

            Lecture lecture = App.MyStudyService.GetLecture(int.Parse(id));

            viewModel = new LectureViewModel(lecture, App.MyStudyService);
            DataContext = viewModel;

            if (!viewModel.IsDataLoaded)
            {
                viewModel.Refresh();
            }
        }

        private void Messages_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MessageViewModel message = ((ListBox)sender).SelectedItem as MessageViewModel;
            if (null != message)
            {
                NavigationService.Navigate(new Uri("/Pages/MessagePage.xaml?id=" + message.Id, UriKind.Relative));
                ((ListBox)sender).SelectedIndex = -1;
            }
        }

        private void Persons_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            PersonViewModel person = ((ListBox)sender).SelectedItem as PersonViewModel;
            if (null != person)
            {
                NavigationService.Navigate(new Uri("/Pages/PersonPage.xaml?id=" + person.Id, UriKind.Relative));
                ((ListBox)sender).SelectedIndex = -1;
            }
        }

        private void Website_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask();
            task.URL = viewModel.Url;

            task.Show();
        }

        private void Details_Click(object sender, RoutedEventArgs e)
        {
            viewModel.ToggleDetails();

            if (viewModel.DetailsExpanded == 96)
            {
                details.Content = "Details anzeigen";
            }
            else
            {
                details.Content = "Details ausblenden";
            }
        }

        private void SyncMessages_Click(object sender, EventArgs e)
        {

        }
    }
}